package com.itany.book.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.mapper.UserMapper;
import com.itany.pojo.User;
import com.itany.pojo.UserExample;
import com.itany.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Transactional(readOnly = true)
    public PageInfo<User> findUserAll(Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        List<User> list = userMapper.selectByExample(new UserExample());
        PageInfo<User> info = new PageInfo<User>(list);
        return info;
    }

    public PageInfo<User> findUserByExample(Integer page, Integer rows, String username, Integer flag) {
        //


        UserExample example = new UserExample();
        UserExample.Criteria cl = example.or();
        if (flag != null && flag != -1) {//状态条件查询
            cl.andFlagEqualTo(flag);
        }
        if (username != null) {//用户名条件查询
            cl.andUsernameLike("%" + username + "%");
        }

        PageHelper.startPage(page, rows);
        List<User> list = userMapper.selectByExample(example);
        PageInfo<User> info = new PageInfo<User>(list);
        return info;
    }

    public void updateStatus(Integer id, Integer flag) {
        User user = new User();
        user.setFlag(flag);
        user.setId(id);
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Transactional(readOnly = true)
    public User findOne(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public void modify(Integer id, String username, String phone, String email, String interest) {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPhone(phone);
        user.setEmail(email);
        user.setInterest(interest);

        userMapper.updateByPrimaryKeySelective(user);
    }
}

